package com.sirui.x.util;

import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sirui.x.global.ServiceException;

public class JacksonUtil {

	private static final ObjectMapper mapper;
	
	static {
		mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}
	
	public static ObjectMapper getObjectMapper() {
		return mapper;
	}
	
	public static String bean2String(Object obj) {
		try {
			return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	public static <T> T string2Bean(String json, Class<T> valueType) {
		try {
			return mapper.readValue(json, valueType);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	public static <T> T string2Bean(String json, TypeReference<T> typeReference) {
		try {
			return mapper.readValue(json, typeReference);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	public static JsonNode string2Json(String json) {
		try {
			return mapper.readTree(json);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	public static String json2String(JsonNode jsonNode) {
		try {
			return mapper.writeValueAsString(jsonNode);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	public static <T> T json2Bean(JsonNode jsonNode, Class<T> valueType) {
		try {
			return mapper.treeToValue(jsonNode, valueType);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	public static JsonNode bean2Json(Object obj) {
		try {
			return mapper.valueToTree(obj);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
}
